using System;
using System.Collections.Generic;
using UnityEngine;

namespace XGame
{
    public class UnityMainThreadDispatcher : MonoBehaviour
    {

        private static UnityMainThreadDispatcher _instance;
        private static readonly Queue<Action> _executionQueue = new Queue<Action>();

        // 获取 UnityMainThreadDispatcher 实例的方法
        public static UnityMainThreadDispatcher Instance()
        {
            if (_instance != null)
            {
                return _instance; // 如果已经存在实例，直接返回
            }

            // 查找是否已经有一个名为 "Global" 的对象
            GameObject global = GameObject.Find("Global");

            if (global != null)
            {
                // 如果有 Global 对象，查找它下是否有 "UnityMainThreadDispatcher" 子物体
                Transform dispatcherTransform = global.transform.Find("UnityMainThreadDispatcher");
                if (dispatcherTransform != null)
                {
                    // 如果有子物体 UnityMainThreadDispatcher，获取该组件
                    _instance = dispatcherTransform.GetComponent<UnityMainThreadDispatcher>();
                }

                if (_instance == null)
                {
                    // 如果没有找到组件，添加一个 UnityMainThreadDispatcher 组件
                    GameObject dispatcherObject = new GameObject("UnityMainThreadDispatcher");
                    dispatcherObject.transform.SetParent(global.transform); // 设置为 Global 的子物体
                    _instance = dispatcherObject.AddComponent<UnityMainThreadDispatcher>();
                }
            }
            else
            {
                // 如果没有找到 Global 对象，则创建 Global 和 UnityMainThreadDispatcher
                GameObject globalObject = new GameObject("Global");
                DontDestroyOnLoad(globalObject); // 防止在场景切换时销毁
                GameObject dispatcherObject = new GameObject("UnityMainThreadDispatcher");
                dispatcherObject.transform.SetParent(globalObject.transform); // 设置为 Global 的子物体
                _instance = dispatcherObject.AddComponent<UnityMainThreadDispatcher>();
            }

            return _instance;
        }

        // 每一帧执行队列中的任务
        void Update()
        {
            while (_executionQueue.Count > 0)
            {
                _executionQueue.Dequeue().Invoke(); // 执行队列中的所有任务
            }
        }

        // 将任务加入到执行队列
        public void Enqueue(Action action)
        {
            lock (_executionQueue)
            {
                _executionQueue.Enqueue(action);
            }
        }

    }
}
